package com.itheima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.VO.WmUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.WmUserDTO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.mededia.pojo.WmUser;
import com.heima.utils.common.AppJwtUtil;
import com.itheima.common.exception.CustException;
import com.itheima.wemedia.mapper.WMuserMapper;
import com.itheima.wemedia.service.WMUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;

@Service
public class WMUserServiceImpl extends ServiceImpl<WMuserMapper, WmUser> implements WMUserService {
    @Override
    public ResponseResult login(WmUserDTO dto) {
        //1 校验参数
        if (StringUtils.isBlank(dto.getName())  || StringUtils.isBlank(dto.getPassword())){
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 查询自媒体用户
        WmUser user = getOne(Wrappers.<WmUser>lambdaQuery().eq(WmUser::getName, dto.getName()));
        if (user==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户不存在");
        }
        if (!DigestUtils.md5DigestAsHex((dto.getPassword()+user.getSalt()).getBytes()).equals(user.getPassword())){
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR,"用户名或者密码输入错误");
        }
        if (user.getStatus()!=9){
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR);
        }

        //4 返回jwt结果
        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
        WmUserVO wmUserVO = new WmUserVO();
        BeanUtils.copyProperties(user,wmUserVO);
        String token = AppJwtUtil.getToken(user.getId().longValue());
        stringObjectHashMap.put("token",token);
        stringObjectHashMap.put("user",wmUserVO);

        return ResponseResult.okResult(stringObjectHashMap);
    }
}
